package com.article.controller.system;

import com.article.dto.ReturnError;
import com.article.enums.ReturnInfoEnum;
import com.article.exception.RecordHaveException;
import com.article.model.MenuInfo;
import com.article.model.RoleInfo;
import com.article.service.MenuInfoService;
import com.article.service.RoleInfoService;
import com.article.utils.RightsHelper;
import com.article.utils.StringUtil;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigInteger;
import java.util.*;

/**
 * Created by Administrator on 2017/5/3.
 */
@RestController
@RequestMapping("/auth")
public class AuthController {
    private final static byte[] lock = new byte[0]; // 特殊的instance变量
    private final static Logger logger = LoggerFactory.getLogger(AuthController.class);
    @Autowired
    private RoleInfoService roleInfoService;
    @Autowired
    private MenuInfoService menuInfoService;

    @RequestMapping(value = "/listRoles", method = RequestMethod.POST)
    public ReturnError listRoles(@RequestParam(name = "key", required = false) String key,
                                 @RequestParam(name = "pageIndex", required = true, defaultValue = "0") Integer pageIndex,
                                 @RequestParam(name = "limit", required = true, defaultValue = "10") Integer limit) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<RoleInfo> roleInfos = new ArrayList<RoleInfo>();
        try {
            if (StringUtil.isNotEmpty(key)) {
                map.put("roleNameLike", key);
            }
            PageInfo<RoleInfo> p = roleInfoService.listByPage(pageIndex + 1, limit, map);
            return new ReturnError(false, null, p.getTotal(), p.getList());
        } catch (Exception e) {
            return new ReturnError(true, ReturnInfoEnum.ERROR.getInfo(), 0L, null);
        }
    }


    @RequestMapping(value = "/saveRole", method = RequestMethod.POST)
    public ReturnError saveRole(RoleInfo roleInfo) {
        try {
            if (StringUtil.isEmpty(roleInfo.getRoleName())) {
                return new ReturnError(true, ReturnInfoEnum.EMPTY.getType(), "请输入角色名", null);
            }
            roleInfo.setGmtCreate(Calendar.getInstance().getTime());
            roleInfo.setGmtModified(roleInfo.getGmtCreate());
            return roleInfoService.saveRole(roleInfo);
        } catch (RecordHaveException e) {
            return new ReturnError(true, ReturnInfoEnum.FAIL.getType(), e.getMessage(), null);
        } catch (Exception e) {
            logger.info(ReturnInfoEnum.ERROR.getType(), e);
            return new ReturnError(true, ReturnInfoEnum.ERROR.getType(), ReturnInfoEnum.ERROR.getInfo(), null);
        }
    }

    @RequestMapping(value = "/updateRole", method = RequestMethod.POST)
    public ReturnError updateRole(@RequestParam(name = "id", required = true) Long id, String roleName) {
        try {
            if (StringUtil.isEmpty(roleName)) {
                return new ReturnError(true, ReturnInfoEnum.EMPTY.getType(), "请输入角色名", null);
            }
            RoleInfo roleInfo = roleInfoService.getById(id);
            if (roleInfo == null) {
                return new ReturnError(true, ReturnInfoEnum.NORECORD.getType(), ReturnInfoEnum.NORECORD.getInfo(), null);
            }
            roleInfo.setRoleName(roleName);
            roleInfo.setGmtModified(Calendar.getInstance().getTime());
            return roleInfoService.updateRole(roleInfo);
        } catch (Exception e) {
            logger.info(ReturnInfoEnum.ERROR.getType(), e);
            return new ReturnError(true, ReturnInfoEnum.ERROR.getType(), ReturnInfoEnum.ERROR.getInfo(), null);
        }
    }

    @RequestMapping(value = "/removeRole", method = RequestMethod.POST)
    public ReturnError removeRole(@RequestParam(name = "ids", required = true) String ids) {
        try {
            return roleInfoService.removeRole(ids);
        } catch (Exception e) {
            logger.info(ReturnInfoEnum.ERROR.getType(), e);
            return new ReturnError(true, ReturnInfoEnum.ERROR.getType(), ReturnInfoEnum.ERROR.getInfo(), null);
        }
    }


    @RequestMapping(value = "/loadAuth", method = RequestMethod.POST)
    public ReturnError loadAuth(@RequestParam(name = "roleId", required = true) Long roleId) throws Exception {
        JSONObject jsonObject = null;
        JSONArray jsonArray = null;
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(new String[]{"menuId", "menuUrl", "menuFlag", "menuDesc", "sort", "gmtCreate",
                "gmtModified"});
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            RoleInfo roleInfo = roleInfoService.getById(roleId);
            List<MenuInfo> menuInfoList = menuInfoService.listByMap(map);
            for (MenuInfo menuInfo : menuInfoList) {
                menuInfo.setHasMenu(RightsHelper.testRights(roleInfo.getRoleRights(), "" + menuInfo.getId()));
            }
            jsonArray = JSONArray.fromObject(menuInfoList, jsonConfig);
            String json = jsonArray.toString();
            json = json.replace("parentId", "pId").replace("menuName", "name").replace("hasMenu",
                    "checked");
            return new ReturnError(false, ReturnInfoEnum.SUCCESS.getType(), json);
        } catch (Exception e) {
            logger.info(ReturnInfoEnum.ERROR.getType(), e);
            return new ReturnError(true, ReturnInfoEnum.ERROR.getType(), ReturnInfoEnum.ERROR.getInfo(), null);
        }
    }

    @RequestMapping(value = "/updAuth", method = RequestMethod.POST)
    public ReturnError updAuth(@RequestParam(name = "id", required = true) Long roleId,
                               @RequestParam(name = "ids", required = true, defaultValue = "1") String ids) {
        try {
            RoleInfo roleInfo = roleInfoService.getById(roleId);
            if (roleInfo == null) {
                return new ReturnError(true, ReturnInfoEnum.NORECORD.getType(), ReturnInfoEnum.NORECORD.getInfo(), null);
            }
            BigInteger rights = RightsHelper.sumRights(ids.split(","));
            roleInfo.setRoleRights(rights.toString());
            roleInfo.setGmtModified(Calendar.getInstance().getTime());
            roleInfoService.updateRole(roleInfo);
            return new ReturnError(false, ReturnInfoEnum.SUCCESS.getType(), ReturnInfoEnum.SUCCESS.getInfo(), null);
        } catch (Exception e) {
            logger.info(ReturnInfoEnum.ERROR.getType(), e);
            return new ReturnError(true, ReturnInfoEnum.ERROR.getType(), ReturnInfoEnum.ERROR.getInfo(), null);
        }
    }
}
